package com.thejupitech;


import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class BooksActivity extends ListActivity implements OnItemClickListener, OnScrollListener {
	public static final int VIEW_BOOK_DETAILS = 999;
	public static final int LOAD_MORE_ITEM = 998;
	private final int itemsLimit = 400;
	private int firstSaved = 0;
	private int items = 0;
	private boolean isDataExist = true;
	private boolean isLoading = false;
	private ProgressDialog progDialog;
	private LazyAdapter adapter;
	private String url;
	private String strKeyword;
	int statusActivity = 0;
	int page = 1;
	private ArrayList<HashMap<String, String> > booksList = new ArrayList<HashMap<String,String>>();
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.books_layout);
		Bundle bleReceiver = this.getIntent().getExtras();
		strKeyword = bleReceiver.getString("key");
		
	  //Loading data from internet			
		url = "http://booksearch.sg/books/search/keyword/page/xml";				
		setDataIntoListView(strKeyword, url);
		//fill data into listview
		adapter=new LazyAdapter(BooksActivity.this, booksList);
		setListAdapter(adapter);
		setTitle("Found " + items + " results");
		
		this.getListView().setOnItemClickListener(this);
		//Set scroll event
		this.getListView().setOnScrollListener(this);

	}
	
	//Set data into ListView
	private void setDataIntoListView(String strKeyword, String url) {
		url = url.replace("page", String.valueOf(page++));
		String strXml = XmlBookParser.getBooksXml(strKeyword, url);
		strXml = strXml.replace("&", "&amp;");
		
		Document doc = XmlBookParser.getXmlFromString(strXml);	
		NodeList nodes = doc.getElementsByTagName("book");
		if(nodes.getLength() == 0) {
			isDataExist=false;
		}
		
		if(nodes.getLength() <10 && nodes.getLength() > 0) {
			isDataExist = false;
		}
		//get data from xml
		for(int i = 0; i < nodes.getLength(); i++) {
			HashMap<String , String> map = new HashMap<String, String>();
			String strAuthor = "";	
			
			Element e = (Element)nodes.item(i);

			map.put("isbn","ISBN: " + XmlBookParser.getValue(e, "isbn"));
			map.put("title","Title: " + XmlBookParser.getValue(e, "title"));

			//Get author's values
			NodeList authorNodes = e.getElementsByTagName("author");
			for(int index = 0; index < authorNodes.getLength(); index++) {
				
				Element elmAuthors = (Element) authorNodes.item(index);
				strAuthor += XmlBookParser.getValue(elmAuthors, "author") + ". ";
			}
			map.put("author", "Author: " + strAuthor);
			map.put("image",XmlBookParser.getValue(e, "image"));
			booksList.add(map);		
		}
		items+=nodes.getLength(); 	

		return;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	 private class LoadingData extends AsyncTask<Bundle, Void, Void> {

			@Override
			protected Void doInBackground(Bundle... params) {
				switch(statusActivity) {
				case VIEW_BOOK_DETAILS:
					Intent iDetails = new Intent(BooksActivity.this, BookDetailsActivity.class);
					iDetails.putExtras(params[0]);
					startActivity(iDetails);
					break;
				case LOAD_MORE_ITEM:					
					setDataIntoListView(strKeyword, url);					
					break;
				default:
					return null;
				}
				return null;							
			}
			@Override
			protected void onPostExecute(Void result) {
				switch(statusActivity) {
				case VIEW_BOOK_DETAILS:
					adapter.imageLoader.clearCache();
			        adapter.notifyDataSetChanged();	
					progDialog.dismiss();
//					finish();
					break;
				case LOAD_MORE_ITEM:
					runOnUiThread(new Runnable() {					
						public void run() {
							// TODO Auto-generated method stub
							adapter.notifyDataSetChanged();							
							setTitle("Found " + items + " results");
							isLoading = false;
						}
					});
										
					break;
				}
			}
	   }

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		String isbnTemp = booksList.get(position).get("isbn");
		String isbn = isbnTemp.replace("ISBN: ", "");
		if (!isbn.equals("")) {
			Bundle sendBundle = new Bundle();
			sendBundle.putString("isbn key", isbn);
			statusActivity = VIEW_BOOK_DETAILS;
			progDialog = ProgressDialog.show(BooksActivity.this, "Getting data", "Loading...");
			new LoadingData().execute(sendBundle);
		} else {
			Toast.makeText(BooksActivity.this, "Cannot retrieve books' isbn.", Toast.LENGTH_LONG).show();
		}	
	}


	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;
		
		//detect if last item is visible
		if((visibleItemCount < totalItemCount) && (lastInScreen == totalItemCount)&& (totalItemCount<itemsLimit) && !(isLoading)) {
			if(isDataExist) {
				isLoading = true;
				statusActivity = LOAD_MORE_ITEM;
				Toast.makeText(BooksActivity.this, "LOADING...", Toast.LENGTH_SHORT).show();
				new LoadingData().execute();
			} else if(firstSaved < 1) {
				firstSaved++;
				Toast.makeText(BooksActivity.this, "DONE", Toast.LENGTH_SHORT).show();
			}
		} 
		if(totalItemCount == itemsLimit && firstSaved < 1) {
			firstSaved++;
			Toast.makeText(BooksActivity.this, "MAXIMUM RESULT", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// No use but need for interface
	}

	@Override
	public void onBackPressed() {		
		startActivity(new Intent(BooksActivity.this, BookSearchActivity.class));
		adapter.imageLoader.clearCache();
		finish();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub		
		adapter.notifyDataSetChanged();
		if(isLoading==true){ 
			isLoading=false;
		}
		setTitle("Found " + items + " results");
		super.onResume();
	}

	@Override
	protected void onRestoreInstanceState(Bundle state) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(state);
		items = state.getInt("items");
		page = state.getInt("page");
		statusActivity = state.getInt("status");
		firstSaved = state.getInt("firstsaved");
		isDataExist = state.getBoolean("is exist");
		isLoading = state.getBoolean("is loading");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		outState.putInt("items", items);
		outState.putInt("page", page);
		outState.putInt("status", statusActivity);
		outState.putInt("firstsaved", firstSaved);
		outState.putBoolean("is exist", isDataExist);
		outState.putBoolean("is loading", isLoading);		
		super.onSaveInstanceState(outState);
	}
	
	
}
